// miniprogram/addActive/add/add.js
const app = getApp()
import activeApi from '../../api/activeApi'
import msgCheck from '../../util/msgCheck'

import imgCheck from '../../util/imgCheck'
import uploadImgList from '../../util/uploadImgList'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: '',

    content: '',
    imgList: [],
    fileList: [],
    date:'',
 
    address: '',

    deleteFiles: []
  },
  pageData:{
    latitude:'',
    longitude:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
   
    this.setData({
      action: options.action
    })
    if(options.action == 'update'){
      
      this.getDetail(options.activeId)
    } else {
      var active = wx.getStorageSync("active")
      wx.removeStorageSync('active')
      if(active){
        console.log(active)
        this.setData({
          content : active.content,
          imgList : active.imgList,
        
          date : active.date,
        
          address : active.address
        })
        
        this.pageData.latitude = active.location.coordinates[1];
        this.pageData.longitude = active.location.coordinates[0];
      }
    }
  },
  async getDetail(activeId){
    wx.showLoading({
      mask: true
    })

    var res = await activeApi.getActive(activeId)
    res = res[0]

    wx.hideLoading()
    
    this.setData({
      content: res.content,
      imgList: res.imgList,
      fileList: res.fileList,
      address: res.address,
      active: res,
      date: res.date
    })
    if(res.location){
      this.pageData.latitude = res.location.coordinates[1];
      this.pageData.longitude = res.location.coordinates[0];
    }
    

    
  },
  dateChange(e){
    this.data.date = e.detail
  }, 
  previewImage(e){
    var url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: this.data.imgList,
      current: url
    })
  },
  chooseLocation(){
    var opt = {
     
      success:(res) => {
        console.log(res)
        var name = res.name;
        this.pageData.address = res.address;
        this.pageData.latitude = res.latitude;
        this.pageData.longitude = res.longitude;
        this.setData({
          address:name
        })
      },
      fail:(res) => {
        wx.openSetting({
          success(res) {
            console.log(res.authSetting)
          }
        })
      },
      complete: (res) => {

      }
    }
    
    if(this.pageData.latitude){
      opt. latitude = this.pageData.latitude
    }
    if(this.pageData.longitude){
      opt. longitude = this.pageData.longitude
    }
    wx.chooseLocation(opt)
  },
  bindDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },
  contentInput: function(e) {
    var val = e.detail.value;

    this.setData({
      content: val
    });
  },
  chooseImage:function(){
    wx.chooseMedia({
        count: 9 - this.data.imgList.length,
        mediaType: ['image'],
        success: (res) => {
         let list = res.tempFiles.map(obj => obj.tempFilePath)

          const tempFilePaths = this.data.imgList.concat(list)
          this.setData({
            imgList: tempFilePaths
          })
        }
      })
  },

  delImg(e){
    this.data.active
    var index = e.currentTarget.dataset.index
    this.data.imgList.splice(index,1)
    var fileIds = this.data.fileList.splice(index,1)
    if(fileIds[0]){
      this.data.deleteFiles.push(fileIds[0])
    }
    this.setData({
      imgList: this.data.imgList
    })
  },

  

  async addActive(){
    let pass = await msgCheck(this.data.content)
   if(!pass){
      return
   }

   pass =  await imgCheck(this.data.imgList)
   if(!pass){
    return
 }
     

    if(this.data.imgList.length == 0 && (!this.data.content)){
      wx.showToast({
        title:'没有可提交的内容',
        icon:'none'
      })
      return 
    }

    wx.showLoading({
      mask:true
    })
    var res = await uploadImgList(this.data.imgList, this.data.fileList)
    
    var params = {
      openid : app.globalData.openid,
      avatarUrl : '',
      nickName : '',
      content:  this.data.content,
      fileList: res.map((f) => f.fileID),
      imgList: res.map((f) => f.tempFileURL),
      date:  this.data.date,
      address :  this.data.address,
      
    }
  
    
    if(this.pageData.longitude){
      params.longitude = this.pageData.longitude,
      params.latitude = this.pageData.latitude
    }

    if(this.data.action == 'update') {
      
      params.id = this.data.active._id
      var paramsCopy = JSON.parse(JSON.stringify(params))
      var data = await activeApi.updateActive(params)
      
      data = await wx.cloud.deleteFile({
        fileList: this.data.deleteFiles
      })
      
     
      
      wx.setStorageSync('updateActiveDate', paramsCopy)
      wx.navigateBack()
    } else {
     
      var data = await activeApi.addActive(params)
      wx.showToast({
        title: '添加成功',
      })
      
      params.id = data
     

      wx.setStorageSync('addActive', 1)
      wx.redirectTo({
        url: '/pages/activeDetail/activeDetail?activeId=' + data
      })
    }
    wx.hideLoading()
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
//   onShareAppMessage: function () {
//     return {
//       title: '这是一个记事本备忘录',
//       imageUrl: 'https://public-server-center-prod-1258963190.cos.ap-guangzhou.myqcloud.com/studentCard/20210521153238.jpg'
//     }
//   }
})